import express from 'express';
import cors from 'cors';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';

const app = express();

app.use(cors());
app.use(express.json());

// 简单的内存数据库（实际项目中应该用MongoDB）
let users = [
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    password: '$2a$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/eoZB3/5TQcRbSjOTW' // 123456
  }
];

let products = [
  {
    id: 1,
    name: 'HUAWEI Pura70 Pro+',
    price: 8979,
    description: '旗舰影像手机',
    image: '/images/pura70-pro-plus.jpg'
  },
  {
    id: 2,
    name: 'HUAWEI Pura70 Pro',
    price: 6999,
    description: '专业影像手机',
    image: '/images/pura70-pro.jpg'
  },
  {
    id: 3,
    name: 'HUAWEI Pura70',
    price: 5499,
    description: '时尚影像手机',
    image: '/images/pura70.jpg'
  }
];

const JWT_SECRET = 'your-super-secret-jwt-key';

// 认证中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ 
      success: false, 
      message: '访问被拒绝，请先登录' 
    });
  }

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) {
      return res.status(403).json({ 
        success: false, 
        message: 'Token无效或已过期' 
      });
    }
    req.user = user;
    next();
  });
};

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ 
    success: true, 
    message: '后端服务运行正常' 
  });
});

// 用户注册
app.post('/api/auth/register', async (req, res) => {
  try {
    const { username, email, password } = req.body;

    // 验证输入
    if (!username || !email || !password) {
      return res.status(400).json({
        success: false,
        message: '请填写所有必填字段'
      });
    }

    if (password.length < 6) {
      return res.status(400).json({
        success: false,
        message: '密码长度至少6位'
      });
    }

    // 检查用户是否已存在
    const existingUser = users.find(user => 
      user.email === email || user.username === username
    );

    if (existingUser) {
      return res.status(400).json({
        success: false,
        message: '用户名或邮箱已存在'
      });
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 12);

    // 创建新用户
    const newUser = {
      id: users.length + 1,
      username,
      email,
      password: hashedPassword
    };

    users.push(newUser);

    // 生成 token
    const token = jwt.sign(
      { userId: newUser.id, username: newUser.username }, 
      JWT_SECRET, 
      { expiresIn: '7d' }
    );

    res.status(201).json({
      success: true,
      message: '注册成功',
      token,
      user: {
        id: newUser.id,
        username: newUser.username,
        email: newUser.email
      }
    });

  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({
      success: false,
      message: '注册失败，请稍后重试'
    });
  }
});

// 用户登录 - 核心功能
app.post('/api/auth/login', async (req, res) => {
  try {
    const { email, password } = req.body;

    console.log('登录请求:', { email, password: password ? '***' : '未提供' });

    // 1. 检查是否提供了邮箱和密码
    if (!email || !password) {
      return res.status(400).json({
        success: false,
        message: '请提供邮箱和密码'
      });
    }

    // 2. 查找用户
    const user = users.find(user => 
      user.email === email || user.username === email
    );

    if (!user) {
      return res.status(401).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 3. 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);
    console.log('密码验证结果:', isPasswordValid);

    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        message: '密码错误'
      });
    }

    // 4. 生成 JWT token
    const token = jwt.sign(
      { userId: user.id, username: user.username }, 
      JWT_SECRET, 
      { expiresIn: '7d' }
    );

    // 5. 返回成功响应
    res.json({
      success: true,
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      }
    });

  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '登录失败，请稍后重试'
    });
  }
});

// 验证 token（用于自动登录）
app.get('/api/auth/verify', authenticateToken, async (req, res) => {
  try {
    const user = users.find(user => user.id === req.user.userId);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '验证失败'
    });
  }
});

// 获取用户信息
app.get('/api/auth/user', authenticateToken, async (req, res) => {
  try {
    const user = users.find(user => user.id === req.user.userId);
    res.json({
      success: true,
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户信息失败'
    });
  }
});

// 原有的产品API保持不变
app.get('/api/product', (req, res) => {
  res.json({
    name: 'HUAWEI Pura70 Pro+',
    price: 8979,
    storage: '256GB',
    details: {
      size: '长度 160 mm 宽度 16.1 mm 厚度 0.3 mm',
      weight: '约 219g（含电池）',
      screen: '6.8 英寸 OLED',
      memory: '16GB RAM + 512GB/1TB ROM'
    }
  });
});

// 产品列表 API
app.get('/api/products', (req, res) => {
  res.json({
    data: products
  });
});

// 需要登录才能访问的受保护路由示例
app.get('/api/protected/products', authenticateToken, (req, res) => {
  res.json({
    success: true,
    message: `欢迎 ${req.user.username}！这是受保护的产品数据`,
    data: products
  });
});

app.listen(3001, () => {
  console.log('🚀 服务器运行在 http://localhost:3001');
  console.log('📝 可用的认证API:');
  console.log('   POST /api/auth/register - 用户注册');
  console.log('   POST /api/auth/login    - 用户登录');
  console.log('   GET  /api/auth/verify   - 验证token');
  console.log('   GET  /api/auth/user     - 获取用户信息');
  console.log('   GET  /api/health        - 健康检查');
  
  // 显示预置的测试账号
  console.log('\n🔐 测试账号:');
  console.log('   用户名: admin');
  console.log('   邮箱: admin@example.com');
  console.log('   密码: 123456');
});